'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var WebUtils = function () {
    function WebUtils() {
        _classCallCheck(this, WebUtils);
    }

    _createClass(WebUtils, null, [{
        key: 'notify',

        /**
         * 网页通知
         *
         * @static
         * @param {string} title 标题
         * @param {string} body 内容
         * @param {string} icon 图标链接
         * @param {string} sound 提示音链接
         * @memberof WebUtils
         */
        value: function notify(title, body, icon, sound) {
            Notification.requestPermission(function (result) {
                if (result == 'granted') {
                    var notification = new Notification(title, {
                        body: body,
                        icon: icon,
                        silent: true
                    });
                    if (sound) {
                        //用h5播放
                        var okexAudio = new Audio(sound);
                        okexAudio.play();
                    }
                    notification.onclick = function () {
                        notification.close();
                    };
                } else {
                    alert('通知提醒已禁止,如需启用，请在浏览器选项里启用');
                }
            });
        }

        /**
         * 元素监听
         *
         * @static
         * @param {object} ele document.querySelector('')
         * @param {func} callback 回调
         * @param {boolean} [observeConfig={attributes: true,childList: true}] 监听配置
         * @returns
         * @memberof WebUtils
         */

    }, {
        key: 'observe',
        value: function observe(ele, callback) {
            var observeConfig = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
                attributes: true,
                childList: true
            };

            var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; //浏览器兼容
            var observer = new MutationObserver(function (mutations) {
                //构造函数回调
                mutations.forEach(function (record) {
                    callback(record);
                });
            });
            observer.observe(ele, observeConfig);
            return observer;
        }

        /**
         * WebSocket连接
         *
         * @static
         * @param {string} serverIP 服务器ip
         * @param {number} serverPort 服务器端口
         * @returns WebSocket实例
         * @memberof WebUtils
         */

    }, {
        key: 'webSocketConnect',
        value: function webSocketConnect(serverIP, serverPort) {
            var self = this;
            var host = 'ws://' + serverIP + ':' + serverPort + '/';
            var socket = void 0;
            try {
                socket = new WebSocket(host);
                socket.onopen = function (msg) {
                    self.WebUtilsSocket = socket;
                    self.log('socket\u8FDE\u63A5\u6210\u529F', 1);
                };
                socket.onmessage = function (msg) {
                    if (typeof msg.data === "string") {
                        self.log('\u6536\u5230\u670D\u52A1\u5668\u6D88\u606F:' + msg.data, 1);
                    } else {
                        self.log('\u6D88\u606F\u7C7B\u578B\u6709\u8BEF', 1);
                    }
                };
                socket.onclose = function (msg) {
                    self.log('socket\u8FDE\u63A5\u5173\u95ED', 1);
                };
            } catch (error) {
                self.log(error);
            }
            return socket;
        }

        /**
         * WebSocket发送消息
         *
         * @static
         * @param {any} socket WebSocket实例
         * @param {string} msg 消息
         * @memberof WebUtils
         */

    }, {
        key: 'webSocketSend',
        value: function webSocketSend(socket, msg) {
            if (socket) {
                var endTokens = '\0';
                msg = '' + msg + endTokens;
                socket.send(msg);
            }
        }

        /**
         * 日志
         *
         * @static
         * @param {string} msg 日志信息
         * @param {number} [logLever=2] 0<1<2<3<4<5 => ALL < DEBUG < INFO < WARN < ERROR < FATAL
         * @memberof WebUtils
         */

    }, {
        key: 'log',
        value: function log(msg) {
            var logLever = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;

            var self = this;
            if ((typeof msg === 'undefined' ? 'undefined' : _typeof(msg)) === 'object') {
                msg = JSON.stringify(msg);
            }
            console.log((0, _moment2.default)().format('YYYY-MM-DD HH:mm:ss.S') + ':' + msg);
            if (logLever > 1 && !!self.WebUtilsSocket && self.WebUtilsSocket.readyState === 1) {
                self.webSocketSend(self.WebUtilsSocket, 'jslog:' + msg);
            }
        }

        /**
         * 异步请求
         *
         * @static
         * @param {function} func 需异步请求的函数，剩余参数传函数所需参数 
         * @returns
         * @memberof WebUtils
         */

    }, {
        key: 'taskRun',
        value: function taskRun(func) {
            var _arguments = arguments;

            return new Promise(function (resolve, reject) {
                if (typeof func !== 'function') {
                    reject('\u51FD\u6570\u6709\u8BEF');
                    return;
                }
                setTimeout(function () {
                    try {
                        var thatArgs = [].concat(Array.prototype.slice.call(_arguments));
                        var funcArgs = thatArgs.splice(1);
                        resolve(func.apply(undefined, _toConsumableArray(funcArgs)));
                    } catch (error) {
                        reject(error);
                    }
                }, 0);
            });
        }
    }]);

    return WebUtils;
}();

exports.default = WebUtils;